package lib

import (
	"bytes"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"xian-codegen/lib/context"
	"xian-codegen/lib/schema"
)

func renderFile(path string, destPath string, data interface{}) error {
	// 读取源文件的内容
	content, err := os.ReadFile(path)
	if err != nil {
		return err
	}

	// 创建一个Template实例，解析文件内容
	tmpl, err := template.New(filepath.Base(path)).Parse(string(content))
	if err != nil {
		return err
	}

	// 创建目标文件
	file, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer file.Close()
	fmt.Printf("create file name => %+v\n", file.Name())
	// 执行模板并写入目标文件
	err = tmpl.Execute(file, data)
	if err != nil {
		return err
	}

	return nil
}

func initOutDir(root string, destRoot string, data interface{}) error {
	return filepath.Walk(root, func(path string, info fs.FileInfo, err error) error {
		if err != nil {
			return err
		}

		relPath, err := filepath.Rel(root, path)
		if err != nil {
			return err
		}

		destPath := filepath.Join(destRoot, relPath)
		tmp, _ := template.New("dirPath").Parse(destPath)
		// 渲染模板到 bytes.Buffer
		var buf bytes.Buffer
		tmp.Execute(&buf, data)

		renderDestPath := strings.Replace(buf.String(), ".tpl", "", -1)
		// 输出渲染后的 HTML
		// 如果是目录，创建对应的目标目录
		if info.IsDir() {
			if err := os.MkdirAll(renderDestPath, info.Mode()); err != nil {
				return err
			}
		} else {
			// 如果是文件，渲染并写入目标文件
			if err := renderFile(path, renderDestPath, data); err != nil {
				return err
			}
		}

		return nil
	})
}

func Codegen(ctx *context.Context, tableSchema *schema.TableConfigItem) {
	templateDir := "/Users/nibiew/Projects/104-OpenSource/xian/xian-codegen/template"
	outDir := "/Users/nibiew/Projects/104-OpenSource/xian/xian-codegen/__out__"
	data := map[string]any{
		"schema":          tableSchema,
		"table":           tableSchema.Opts.Table,
		"mod_slash_table": tableSchema.Opts.FullTableName,
	}
	initOutDir(templateDir, outDir, data)
	columns := tableSchema.Columns
	for _, column := range columns {
		fmt.Printf("columnSchema => %+v\n", column)
	}
}
